package main

import "net"

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	server *Server
}

func NewUser(conn net.Conn, server *Server) *User {
	name := conn.RemoteAddr().String()
	newUser := &User{
		Name:   name,
		Addr:   name,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}
	go newUser.ListenMessages()

	return newUser
}

// listenmessages goroutine
func (this *User) ListenMessages() {
	for {
		message := <-this.C
		this.conn.Write([]byte(message + "\n"))
	}
}

func (this *User) OnLine() {
	this.server.mapLock.Lock()
	this.server.OnLineMap[this.Name] = this
	this.server.mapLock.Unlock()
	this.server.BroadCast(this, "已上线")
}

func (this *User) OffLine() {
	this.server.mapLock.Lock()
	delete(this.server.OnLineMap, this.Name)
	this.server.mapLock.Unlock()
	this.server.BroadCast(this, "已下线")
}

func (this *User) SendMsg(msg string) {
	this.conn.Write([]byte(msg))
}

func (this *User) DoMessage(message string) {
	if message == "who" {
		this.server.mapLock.Lock()
		for _, user := range this.server.OnLineMap {
			msg := "[" + user.Addr + "]:" + user.Name + "在线\n"
			this.SendMsg(msg)
		}
		this.server.mapLock.Unlock()
	} else {
		this.server.BroadCast(this, message)
	}
}
